#!/usr/bin/env python3
"""
FlowPlan API 集成测试脚本
测试核心API端点的可用性和基本功能
"""

import requests
import json
import time
import sys
from typing import Dict, Optional

class FlowPlanAPITester:
    def __init__(self, base_url: str = "http://localhost:8080"):
        self.base_url = base_url
        self.api_url = f"{base_url}/api"
        self.token: Optional[str] = None
        self.test_results = []

    def log_test(self, test_name: str, success: bool, message: str = ""):
        """记录测试结果"""
        status = "✓ PASS" if success else "✗ FAIL"
        print(f"{status} {test_name}: {message}")
        self.test_results.append({
            "test": test_name,
            "success": success,
            "message": message
        })

    def test_health_check(self) -> bool:
        """测试健康检查端点"""
        try:
            response = requests.get(f"{self.base_url}/actuator/health", timeout=10)
            success = response.status_code == 200
            self.log_test("Health Check", success, f"Status: {response.status_code}")
            return success
        except Exception as e:
            self.log_test("Health Check", False, f"Error: {str(e)}")
            return False

    def test_login(self) -> bool:
        """测试用户登录"""
        try:
            login_data = {
                "username": "admin",
                "password": "flowplan123"
            }
            response = requests.post(
                f"{self.api_url}/auth/login",
                json=login_data,
                timeout=10
            )
            
            if response.status_code == 200:
                data = response.json()
                if data.get("success") and data.get("data", {}).get("token"):
                    self.token = data["data"]["token"]
                    self.log_test("User Login", True, "Login successful, token received")
                    return True
                else:
                    self.log_test("User Login", False, "No token in response")
                    return False
            else:
                self.log_test("User Login", False, f"Status: {response.status_code}")
                return False
        except Exception as e:
            self.log_test("User Login", False, f"Error: {str(e)}")
            return False

    def test_auth_me(self) -> bool:
        """测试获取当前用户信息"""
        if not self.token:
            self.log_test("Get Current User", False, "No token available")
            return False
            
        try:
            headers = {"Authorization": f"Bearer {self.token}"}
            response = requests.get(
                f"{self.api_url}/auth/me",
                headers=headers,
                timeout=10
            )
            
            success = response.status_code == 200
            message = f"Status: {response.status_code}"
            if success:
                data = response.json()
                if data.get("success"):
                    user = data.get("data", {})
                    message += f", User: {user.get('username', 'unknown')}"
                    
            self.log_test("Get Current User", success, message)
            return success
        except Exception as e:
            self.log_test("Get Current User", False, f"Error: {str(e)}")
            return False

    def test_projects_list(self) -> bool:
        """测试获取项目列表"""
        if not self.token:
            self.log_test("Get Projects", False, "No token available")
            return False
            
        try:
            headers = {"Authorization": f"Bearer {self.token}"}
            response = requests.get(
                f"{self.api_url}/projects",
                headers=headers,
                timeout=10
            )
            
            success = response.status_code == 200
            message = f"Status: {response.status_code}"
            if success:
                data = response.json()
                if data.get("success"):
                    projects = data.get("data", {}).get("content", [])
                    message += f", Projects count: {len(projects)}"
                    
            self.log_test("Get Projects", success, message)
            return success
        except Exception as e:
            self.log_test("Get Projects", False, f"Error: {str(e)}")
            return False

    def test_todos_list(self) -> bool:
        """测试获取待办列表"""
        if not self.token:
            self.log_test("Get Todos", False, "No token available")
            return False
            
        try:
            headers = {"Authorization": f"Bearer {self.token}"}
            response = requests.get(
                f"{self.api_url}/todos",
                headers=headers,
                timeout=10
            )
            
            success = response.status_code == 200
            message = f"Status: {response.status_code}"
            if success:
                data = response.json()
                if data.get("success"):
                    todos = data.get("data", {}).get("content", [])
                    message += f", Todos count: {len(todos)}"
                    
            self.log_test("Get Todos", success, message)
            return success
        except Exception as e:
            self.log_test("Get Todos", False, f"Error: {str(e)}")
            return False

    def test_ai_status(self) -> bool:
        """测试AI服务状态"""
        try:
            response = requests.get(
                f"{self.api_url}/ai/status",
                timeout=10
            )
            
            success = response.status_code == 200
            message = f"Status: {response.status_code}"
            if success:
                data = response.json()
                if data.get("success"):
                    ai_status = data.get("data", {})
                    enabled_features = []
                    if ai_status.get("requirementAnalysisEnabled"):
                        enabled_features.append("Analysis")
                    if ai_status.get("documentGenerationEnabled"):
                        enabled_features.append("Document")
                    if ai_status.get("smartSuggestionsEnabled"):
                        enabled_features.append("Suggestions")
                    message += f", Features: {', '.join(enabled_features)}"
                    
            self.log_test("AI Service Status", success, message)
            return success
        except Exception as e:
            self.log_test("AI Service Status", False, f"Error: {str(e)}")
            return False

    def run_all_tests(self) -> bool:
        """运行所有测试"""
        print(f"🚀 开始FlowPlan API集成测试...")
        print(f"📍 目标服务器: {self.base_url}")
        print("-" * 60)
        
        # 等待服务启动
        print("⏳ 等待服务启动...")
        time.sleep(2)
        
        # 执行测试
        tests = [
            self.test_health_check,
            self.test_login,
            self.test_auth_me,
            self.test_projects_list,
            self.test_todos_list,
            self.test_ai_status,
        ]
        
        passed = 0
        total = len(tests)
        
        for test in tests:
            if test():
                passed += 1
            time.sleep(0.5)  # 避免请求过快
        
        print("-" * 60)
        print(f"📊 测试结果: {passed}/{total} 通过")
        
        if passed == total:
            print("🎉 所有测试通过！系统集成正常。")
            return True
        else:
            print("⚠️  部分测试失败，请检查服务状态。")
            return False

    def generate_report(self) -> None:
        """生成测试报告"""
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
        
        report = {
            "timestamp": timestamp,
            "base_url": self.base_url,
            "total_tests": len(self.test_results),
            "passed_tests": sum(1 for r in self.test_results if r["success"]),
            "failed_tests": sum(1 for r in self.test_results if not r["success"]),
            "results": self.test_results
        }
        
        # 保存JSON报告
        with open("test-report.json", "w", encoding="utf-8") as f:
            json.dump(report, f, indent=2, ensure_ascii=False)
        
        print(f"📄 测试报告已保存到: test-report.json")

def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description="FlowPlan API集成测试")
    parser.add_argument(
        "--url", 
        default="http://localhost:8080",
        help="后端服务URL (默认: http://localhost:8080)"
    )
    parser.add_argument(
        "--report", 
        action="store_true",
        help="生成测试报告"
    )
    
    args = parser.parse_args()
    
    tester = FlowPlanAPITester(args.url)
    success = tester.run_all_tests()
    
    if args.report:
        tester.generate_report()
    
    sys.exit(0 if success else 1)

if __name__ == "__main__":
    main()